﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.BackgroundTransfer;
using DBDataContext.Model;
using System.Windows.Media.Imaging;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Navigation;
using System.Diagnostics;
using MangaForYou.Class;

using Microsoft.Phone.Net.NetworkInformation;
using System.Xml.Linq;
using System.Text.RegularExpressions;
namespace WolfGuy
{
    public partial class MangaInfoPage : PhoneApplicationPage
    {        
        #region AppBar
        private void settingPageButton_Click(object sender, EventArgs e)
        {
            string strUri = String.Format("/SettingPage.xaml");
            NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
        }

        private void homePageButton_Click(object sender, EventArgs e)
        {
            string strUri = String.Format("/MainPage.xaml");
            NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
        }

        private void downloadPageButton_Click(object sender, EventArgs e)
        {
            string strUri = String.Format("/DownloadPage.xaml");
            NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
        }

        private void aboutPageButton_Click(object sender, EventArgs e)
        {
            string strUri = String.Format("/AboutPage.xaml");
            NavigationService.Navigate(new Uri(strUri, UriKind.Relative));
        }
        #endregion

        Manga manga = new Manga();
        int intMangaId; // current mangaId
        Chapter curChapter = new Chapter(); // current downloading chapter
        bool isUpdating = false; // flag for updating chapter 

        int ImageIndex = 0; // index of list's images of downloading chapter
        MatchCollection matches; // link of images


        public MangaInfoPage()
        {
            InitializeComponent();

            // Set the page DataContext property to the ViewModel.
            this.DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MangaInfoPage_Loaded);
        }

        private void SetMangaImage()
        {
            try
            {
                using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    //string path = String.Format("Shared/Download/{0}/{1}", manga.FolderName, manga.ImageName);
                    using (IsolatedStorageFileStream isfs = isf.OpenFile(manga.ImageName, FileMode.Open, FileAccess.Read))
                    {
                        byte[] data;

                        // Allocate an array large enough for the entire file
                        data = new byte[isfs.Length];

                        // Read the entire file and then close it
                        isfs.Read(data, 0, data.Length);
                        isfs.Dispose();
                        isfs.Close();



                        // Create memory stream and bitmap
                        MemoryStream ms = new MemoryStream(data);

                        BitmapImage bi = new BitmapImage();

                        // Set bitmap source to memory stream
                        bi.SetSource(ms);


                        // Assign the bitmap image to the image’s source
                        this.imgMangaImage.Source = bi;
                    }
                    isf.Dispose();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Gặp lỗi khi gán giá trị hình ảnh cho truyện: " + ex.Message);
                App.ViewModel.UpdateMangaImageName(manga.MangaId, "SplashScreenImage.jpg");
            }
        }

        private string GetFolderNameByFileLink(string strFileLink)
        {
            int indexOfLastSplash = strFileLink.LastIndexOf("/");
            int indexOfLastDot = strFileLink.LastIndexOf(".");
            int length = indexOfLastDot - indexOfLastSplash;
            return strFileLink.Substring(indexOfLastSplash + 1, length - 1);
        }

        private void DownloadImage(string link)
        {
            try
            {
                // show loading panel
                this.stkLoading.Visibility = Visibility.Visible;
                this.tbkLoading.Text = String.Format("Đang tải: {0}/{1} - {2}", (ImageIndex + 1).ToString(), matches.Count.ToString(), curChapter.ChapterName);
                link = "http://images2-focus-opensocial.googleusercontent.com/gadgets/proxy?container=focus&gadget=a&no_expand=1&resize_h=0&rewriteMime=image%2F*&url=http%3a%2f%2flh4.ggpht.com%2f-6Nb0xhvlCns%2fThHEl_pzDkI%2fAAAAAAAAADc%2fOWCK3RLC1iU%2f001.JPG";
                // Download image
                Uri url = new Uri(link);

                // Get the URI of the file to be transferred from the Tag property
                // of the button that was clicked.
                Uri transferUri = new Uri(Uri.EscapeUriString(link), UriKind.RelativeOrAbsolute);

                // Create the new transfer request, passing in the URI of the file to 
                // be transferred.
                BackgroundTransferRequest transferRequest = new BackgroundTransferRequest(transferUri);

                // Set the transfer method. GET and POST are supported.
                transferRequest.Method = "GET";

                // Get the file name from the end of the transfer URI and create a local URI 
                // in the "transfers" directory in isolated storage.
                // string downloadFile = link.Substring(link.LastIndexOf("/") + 1);
                string downloadFile = ImageIndex.ToString("D3") + ".jpg";
                // file name
                //string fileName = String.Format("{0}@{1}@{2}", chapter.ChapterId, manga.FolderName, downloadFile);
                
                //Uri downloadUri = new Uri("shared/transfers/" + fileName, UriKind.RelativeOrAbsolute);
                Uri downloadUri = new Uri("shared/transfers/" + curChapter.ChapterFileName + "/" + downloadFile, UriKind.RelativeOrAbsolute);

                transferRequest.DownloadLocation = downloadUri;

                //// Pass custom data with the Tag property. In this example, the friendly name
                //// is passed.
                //transferRequest.Tag = fileName;

                transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery; // v1.2

                // Add the transfer request using the BackgroundTransferService. Do this in 
                // a try block in case an exception is thrown.
                try
                {
                    BackgroundTransferService.Add(transferRequest);
                    transferRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferStatusChanged);
                    transferRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(transfer_TransferProgressChanged);
                    //ProcessTransfer(transferRequest);

                    //return true;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    // Remove request if something wrong
                    foreach (var request in BackgroundTransferService.Requests)
                    {
                        if (request.RequestUri == transferRequest.RequestUri)
                        {
                            BackgroundTransferService.Remove(request);
                            break;
                        }
                    }
                    //return false;

                }

                //WebClient webImage = new WebClient();
                //webImage.OpenReadAsync(url);
                //webImage.OpenReadCompleted += new OpenReadCompletedEventHandler(webImage_OpenReadCompleted);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Gặp lỗi khi đang tải nội dung của chương: " + ex.Message);
            }
        }

        void transfer_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            ProcessTransfer(e.Request);
            UpdateUI();
        }

        void transfer_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            UpdateUI();
        }

        private void UpdateRequestsList()
        {
            // The Requests property returns new references, so make sure that
            // you dispose of the old refereneces to avoid memory leaks.
            if (BackgroundTransferService.Requests != null)
            {
                foreach (var request in BackgroundTransferService.Requests)
                {
                    request.Dispose();
                }
            }

            // the Requests property returns a list of new BackgroundTransferRequest objects
            //BackgroundTransferService.Requests = BackgroundTransferService.Requests;
        }

        private void UpdateUI()
        {
            // Update the list of transfer requests
            UpdateRequestsList();

            // If there are 1 or more transfers, hide the "no transfers"
            // TextBlock. IF there are zero transfers, show the TextBlock.
            if (BackgroundTransferService.Requests.Count() > 0)
            {
                //EmptyTextBlock.Visibility = Visibility.Collapsed;
            }
            else
            {
                //EmptyTextBlock.Visibility = Visibility.Visible;
            }

            // Update the TransferListBox with the list of transfer requests.
            //TransferListBox.ItemsSource = BackgroundTransferService.Requests;

        }


        private void ProcessTransfer(BackgroundTransferRequest transfer)
        {
            switch (transfer.TransferStatus)
            {
                case TransferStatus.Completed:

                    // If the status code of a completed transfer is 200 or 206, the
                    // transfer was successful
                    if (transfer.StatusCode == 200 || transfer.StatusCode == 206)
                    {
                        
                    }
                    else if (transfer.StatusCode == 0)
                    {
                        // StatusCode = 0: request is removed from BackgroundTransferService

                        // Do something if you want
                    }
                    else
                    {
                        // This is where you can handle whatever error is indicated by the
                        // StatusCode and then remove the transfer from the queue. 
                        RemoveTransferRequest(transfer.RequestId);

                        if (transfer.TransferError != null)
                        {
                            // Handle TransferError if one exists.


                        }
                    }
                    break;

                //case TransferStatus.WaitingForExternalPower:
                //    {
                //        //MessageBox.Show("The request is waiting for external power to be connected.");
                //        DownloadError(transfer);
                //        break;
                //    }

                //case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode:
                //    {
                //        //MessageBox.Show("The request is waiting for the device to be connected to external power because the user has enabled Battery Saver mode on this device");
                //        DownloadError(transfer);
                //        break;
                //    }

                //case TransferStatus.WaitingForNonVoiceBlockingNetwork:
                //    {
                //        //MessageBox.Show("This device does not have wifi or network connection.");
                //        DownloadError(transfer);
                //        break;
                //    }

                //case TransferStatus.WaitingForWiFi:
                //    {
                //        //MessageBox.Show("This device does not have wifi or network connection.");
                //        DownloadError(transfer);
                //        break;
                //    }
            }
        }

        private void RemoveTransferRequest(string transferID)
        {
            // Use Find to retrieve the transfer request with the specified ID.
            BackgroundTransferRequest transferToRemove = BackgroundTransferService.Find(transferID);

            // Try to remove the transfer from the background transfer service.
            try
            {
                if (transferToRemove != null)
                {
                    BackgroundTransferService.Remove(transferToRemove);
                }
            }
            catch (Exception e)
            {
                // Handle the exception.
                MessageBox.Show(e.Message);
            }
        }

        private void DownloadMangaImage(string urlImage)
        {
            try
            {
                string fileLink = "Shared/transfers/" + manga.FolderName + "/" + manga.FolderName + ".jpg";
                Uri transferUri = new Uri(Uri.EscapeUriString(urlImage), UriKind.RelativeOrAbsolute);
                using (IsolatedStorageFile isofile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!isofile.DirectoryExists("Shared/transfers"))
                    {
                        isofile.CreateDirectory("Shared/transfers");

                    }
                    if (!isofile.DirectoryExists("Shared/transfers/" + manga.FolderName))
                    {
                        isofile.CreateDirectory("Shared/transfers/" + manga.FolderName);
                    }
                }
                BackgroundTransferRequest downloadMangaImage = new BackgroundTransferRequest(transferUri);
                downloadMangaImage.Method = "GET";
                downloadMangaImage.DownloadLocation = new Uri(fileLink, UriKind.RelativeOrAbsolute);
                downloadMangaImage.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(downloadMangaImage_TransferStatusChanged);
                downloadMangaImage.Tag = fileLink;
                BackgroundTransferService.Add(downloadMangaImage);    
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void GetMangaImage(string result)
        {
            try
            {
                // Show loading panel
                this.stkLoading.Visibility = Visibility.Visible;
                this.tbkLoading.Text = "Đang lấy ảnh đại diện...";

                
                string urlImage = VnSharing.GetImage(result);
                // download manga image
                DownloadMangaImage(urlImage);
                //WebClient webGetMangaImage = new WebClient();
                //webGetMangaImage.OpenReadAsync(new Uri(urlImage));
                //webGetMangaImage.OpenReadCompleted +=new OpenReadCompletedEventHandler(webGetMangaImage_OpenReadCompleted);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Gặp lỗi khi đang lấy ảnh đại diện: " + ex.Message);
            }
        }

        private void UpdateListOfChapterFromServer()
        {
            try
            {
                if (isUpdating == true)
                {
                    MessageBox.Show("Đang cập nhật. Vui lòng chờ.");
                }
                else
                {
                    // set updating
                    isUpdating = true;

                    // download html manga page
                    WebClient webGetChapters = new WebClient();
                    Uri url = new Uri(String.Format("{0}Truyen/{1}", VnSharing.SOURCE, manga.DataLinkDownload));
                    webGetChapters.DownloadStringAsync(url);
                    webGetChapters.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webGetChapters_DownloadStringCompleted);

                    // show loading panel
                    this.stkLoading.Visibility = Visibility.Visible;
                    this.tbkLoading.Text = "Đang cập nhật danh sách chương. Vui lòng chờ...";
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi xảy ra khi đang cập nhật danh sách: " + ex.Message);
                isUpdating = false;
                // hide loading panel
                this.stkLoading.Visibility = Visibility.Collapsed;
            }
        }
        

        private void DeleteFiles(string mangaFolderName, string chapterFileName)
        {
            using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string strPattern = String.Format("Shared/Download/{0}/{1}", mangaFolderName, chapterFileName);

                // Delete all files in directory folder
                foreach (string file in isf.GetFileNames(strPattern + "/*"))
                {
                    //fileList.Add((strPattern + directory + "/" + file));
                    isf.DeleteFile(strPattern + "/" + file);
                }

                // Delete all files in sub folder(s)
                foreach (string directory in FindingExistingFilesAndDirectories.GetAllDirectories(strPattern + "/*", isf))
                {
                    foreach (string file in isf.GetFileNames(strPattern + "/" + directory + "/*"))
                    {
                        //fileList.Add((strPattern + directory + "/" + file));
                        isf.DeleteFile(strPattern + "/" + directory + "/" + file);
                    }
                    // Delete sub folder
                    isf.DeleteDirectory(strPattern + "/" + directory);
                }
                // Delete directory folder
                isf.DeleteDirectory(strPattern);
                isf.Dispose();
            }
        }

        //#region Event Handlers

        void MangaInfoPage_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                if (App.ViewModel.AllChapters.Count == 0)
                {
                    this.stkNoData.Visibility = Visibility.Visible;
                    this.stkFunctions.Visibility = Visibility.Collapsed;
                }
                else
                {
                    this.stkNoData.Visibility = Visibility.Collapsed;
                    this.stkFunctions.Visibility = Visibility.Visible;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Gặp lỗi: " + ex.Message);
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs args)
        {
            try
            {
                // Parse data from query
                IDictionary<string, string> parameters = NavigationContext.QueryString;

                // intMangaId = int.Parse(parameters["mangaId"]);
                intMangaId = VnSharing.MANGAID;


                // Get chapters by MangaId
                App.ViewModel.GetChapterListByMangaId(intMangaId, false);

                // Get manga by Id
                manga = App.ViewModel.GetMangaById(intMangaId);

                this.txtMangaName.Text = manga.Name;
                this.txtDescription.Text = manga.Description;

                if (manga.ImageName != "SplashScreenImage.jpg")
                {
                    //XElement xE = new XElement("a", "a", new XAttribute("A", "A"), new
                    SetMangaImage();
                }
                //this.imgMangaImage.Source = "SplashScreenImage.jpg";
            }
            catch (System.OutOfMemoryException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDownload_Click(object sender, RoutedEventArgs e)
        {
            if ((App.Current as App).isAutoDownload == true)
            {
                MessageBox.Show("Bạn đang ở chế độ tải tự động nên không thể tải nội dung này.");
                return;
            }

            var ni = NetworkInterface.NetworkInterfaceType;

            //if (NetworkInterface.GetIsNetworkAvailable() == false)
            if (ni == NetworkInterfaceType.None)
            {
                MessageBox.Show("Bạn không có kết nối internet. Vui lòng thử lại.");
                return;
            }


            try
            {
                Button button = (Button)sender;

                // Get item from control by usiong FindAnchestor
                ListBoxItem lstItem = UIHelper.FindAnchestor<ListBoxItem>(button);
                int index = this.ListChapter.ItemContainerGenerator.IndexFromContainer(lstItem);
                curChapter = (Chapter)this.ListChapter.Items[index];

                // If this chapter is not downloaded (IsDownloaded = 0), start to download it
                if (curChapter.IsDownloaded == 0)
                {
                    MessageBoxResult msgResult = MessageBox.Show("Bạn có muốn tải nội dung này?", "Xác nhận", MessageBoxButton.OKCancel);
                    if (msgResult == MessageBoxResult.OK)
                    {
                        // show loading panel
                        this.stkLoading.Visibility = Visibility.Visible;
                        this.tbkLoading.Text = "Đang tải hình ảnh. Vui lòng chờ...";

                        // update  chapter's downloading status
                        App.ViewModel.UpdateDownloadingById(curChapter.ChapterId);

                        string url = VnSharing.SOURCE + curChapter.ChapterFileLink;
                        WebClient webChapterInfo = new WebClient();
                        webChapterInfo.DownloadStringAsync(new Uri(url));
                        webChapterInfo.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webChapterInfo_DownloadStringCompleted);
                    }
                }
                else
                {
                    // Logic was wrong if code jump here
                    MessageBox.Show("Logic was wrong");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi xảy ra khi download: " + ex.Message);
                // hide loading panel
                this.stkLoading.Visibility = Visibility.Collapsed;
            }
        }

        void webChapterInfo_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            // http://images2-focus-opensocial
            string search = @"(?<="")http://images2-focus-opensocial.+?(?="")";

            Regex rgx = new Regex(search, RegexOptions.IgnoreCase);
            matches = rgx.Matches(e.Result);
            ImageIndex = 0;
            if (matches.Count > 0)
            {
                // Create chapter's folder
                IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
                if (!iso.DirectoryExists("/Shared/transfers/" + curChapter.ChapterFileName))
                {
                    iso.CreateDirectory("/Shared/transfers/" + curChapter.ChapterFileName);
                }

                // Save links to XML file
                
                // Download
                DownloadImage(matches[ImageIndex].Value);
            }
            else
            {
                MessageBox.Show("Gặp lỗi: Sai dữ liệu phân tích");
            }
        }

        void webImage_OpenReadCompleted(object sender, OpenReadCompletedEventArgs arg)
        {
            try
            {
                using (IsolatedStorageFile isofile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    //if (!isofile.DirectoryExists("Shared/Download/" + manga.FolderName))
                    //{
                    //    isofile.CreateDirectory("Shared/Download/" + manga.FolderName);
                    //}

                    if (!isofile.DirectoryExists("Shared/Download/" +  "/" + curChapter.ChapterFileName))
                    {
                        isofile.CreateDirectory("Shared/Download/" + "/" + curChapter.ChapterFileName);
                    }

                    // Create file.
                    string fileLink = "Shared/Download/" + "/" + curChapter.ChapterFileName + "/" + ImageIndex.ToString("D3") + ".jpg";
                    IsolatedStorageFileStream isfs = isofile.CreateFile(fileLink);

                    //Using MemoryStream to prevent OutOfMemoryException
                    byte[] data;
                    data = new byte[arg.Result.Length];
                    arg.Result.Read(data, 0, data.Length);

                    isfs.Write(data, 0, data.Length);
                    isfs.Flush();
                    isfs.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Gặp lỗi khi đang tải hình ảnh: " + ex.Message);
            }

            try
            {
                ImageIndex++;
                if (ImageIndex < matches.Count)
                {
                    DownloadImage(matches[ImageIndex].Value);
                }
                else
                {
                    // Download all image of chapter
                    // Update status of chapter
                    App.ViewModel.UpdateIsDownloadedByChapterId(curChapter.ChapterId);
                    
                    // Hide loading panel
                    this.stkLoading.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }

        void webGetMangaImage_OpenReadCompleted(object sender, OpenReadCompletedEventArgs args)
        {
            string fileLink = "Shared/Download/" + manga.FolderName + "/" + manga.FolderName + ".jpg";
            try
            {
                if (args.Result != null)
                {
                    // save image
                    using (IsolatedStorageFile isofile = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isofile.DirectoryExists("Shared/Download/" + manga.FolderName))
                        {
                            isofile.CreateDirectory("Shared/Download/" + manga.FolderName);
                        }

                        // Create file.

                        IsolatedStorageFileStream isfs = isofile.CreateFile(fileLink);
                        //Using MemoryStream to prevent OutOfMemoryException
                        byte[] data;
                        data = new byte[args.Result.Length];
                        args.Result.Read(data, 0, data.Length);

                        isfs.Write(data, 0, data.Length);
                        isfs.Flush();
                        isfs.Close();
                    }

                    // update manga's ImageName
                    App.ViewModel.UpdateMangaImageName(manga.MangaId, fileLink);
                    SetMangaImage();

                    // Hide loading panel
                    this.stkLoading.Visibility = Visibility.Collapsed;
                }
                else
                {
                    MessageBox.Show("Không thể tải hình ảnh của truyện");
                    // Hide loading panel
                    this.stkLoading.Visibility = Visibility.Collapsed;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Gặp lỗi khi đang tải hình ảnh của truyện: " + ex.Message);
                // Hide loading panel
                this.stkLoading.Visibility = Visibility.Collapsed;
            }
        }

        void webGetChapters_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs args)
        {
            try
            {
                // get list of chapterinfo from html text
                List<VnSharing.ChapterInfo> chapters = VnSharing.GetChapterLinks(args.Result, manga.DataLinkDownload);


                // Get number of chapters
                int countChapter = App.ViewModel.GetNumberOfChapterByMangaId(manga.MangaId);

               

                if (countChapter <= 0) // this manga does not have any chapter
                {
                    foreach (VnSharing.ChapterInfo chapterInfo in chapters)
                    {
                        App.ViewModel.InsertChapter(manga, chapterInfo);
                    }
                }
                else
                {
                    //int countNewChapter = chapters.Count() - countChapter;
                    int count = 1;
                    // insert list of chapter
                    foreach (VnSharing.ChapterInfo chapterInfo in chapters)
                    {
                        if (count <= countChapter)
                        {
                            count++;
                        }
                        else
                        {
                            App.ViewModel.InsertChapter(manga, chapterInfo);
                            //Debug.WriteLine(chapterInfo.Name);
                        }
                    }
                }

               

                // Get list of chapter for Listbox
                App.ViewModel.GetChapterListByMangaId(manga.MangaId, false);

                // hide loading panel
                this.stkLoading.Visibility = Visibility.Collapsed;
                this.stkNoData.Visibility = Visibility.Collapsed;
                this.stkFunctions.Visibility = Visibility.Visible;

                // Load magan image for the first time
                if (manga.ImageName == "SplashScreenImage.jpg")
                {
                    GetMangaImage(args.Result);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Gặp lỗi khi đang cập nhật danh sách chương: " + ex.Message);
            }
        }

        private void btnMove_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btnMove = (Button)sender;

                int chapterId = int.Parse(btnMove.Tag.ToString());
                Chapter chapter = App.ViewModel.GetChaptersById(chapterId);

                string strUri = String.Format("/ContentPage.xaml?mangaName={0}&chapterId={1}&chapterFileName={2}&curIndex={3}", manga.FolderName, chapter.ChapterId, chapter.ChapterFileName, chapter.CurrentIndex);
                NavigationService.Navigate(new Uri(strUri, UriKind.Relative));

            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi xảy ra khi chuyển trang: " + ex.Message);
            }
        }

        private void imgDownloadIcon_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            UpdateListOfChapterFromServer();
        }

        // Delete chapter's files in Isolated Storage 
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MessageBoxResult msgResult = MessageBox.Show("Bạn có chắc chắn muốn xóa nội dung này?", "Xác nhận", MessageBoxButton.OKCancel);
                if (msgResult == MessageBoxResult.OK)
                {

                    // Delete file by using manga folder name and chapter file name
                    Button btnDelete = (Button)sender;

                    int chapterID = (int)btnDelete.Tag;

                    //ListBoxItem lstItem = UIHelper.FindAnchestor<ListBoxItem>(btnDelete);
                    //int index = this.ListChapter.ItemContainerGenerator.IndexFromContainer(lstItem);
                    //Chapter chapter = (Chapter)this.ListChapter.Items[index];
                    Chapter chapter = App.ViewModel.GetChaptersById(chapterID);
                    string mangaFolderName = manga.FolderName;
                    string chapterFileName = chapter.ChapterFileName;

                    // Call delete function
                    DeleteFiles(mangaFolderName, chapterFileName);

                    // Update database by using chapterId
                    //App.ViewModel.UpdateIsDownloadedByChapterId(chapter.ChapterId);
                    App.ViewModel.UpdateNeedToDownloadByChapterId(chapterID);
                    App.ViewModel.UpdateCurrentIndexByChapterID(chapterID, 0);
                    // Enable Download Button
                    //Button btnDownload = new Button();
                    //UIHelper.GetChildByName<Button>(lstItem, "btnDownload", ref btnDownload);
                    //btnDownload.IsEnabled = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Lỗi xảy ra khi xóa dữ liệu: " + ex.Message);
            }
        }

        void downloadMangaImage_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            if (e.Request.TransferStatus == TransferStatus.Completed)
            {
                try
                {
                    // Hide loading panel
                    this.stkLoading.Visibility = Visibility.Collapsed;
                    this.tbkLoading.Text = "";

                    // Update manga image
                    App.ViewModel.UpdateMangaImageName(manga.MangaId, e.Request.Tag);

                    // Set manga image
                    SetMangaImage();

                    //Debug.WriteLine("Download image successful.");

                    BackgroundTransferService.Remove(e.Request);

                    isUpdating = false; 
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void rdbInc_Checked(object sender, RoutedEventArgs e)
        {
            // Get chapters by MangaId
            App.ViewModel.GetChapterListByMangaId(intMangaId, true);
        }

        private void rdbDec_Checked(object sender, RoutedEventArgs e)
        {
            // Get chapters by MangaId
            App.ViewModel.GetChapterListByMangaId(intMangaId, false);
        }

        private void lnkInc_Click(object sender, RoutedEventArgs e)
        {
            // Get chapters by MangaId
            App.ViewModel.GetChapterListByMangaId(intMangaId, true);
        }

        private void lnkDec_Click(object sender, RoutedEventArgs e)
        {
            // Get chapters by MangaId
            App.ViewModel.GetChapterListByMangaId(intMangaId, false);
        }

        private void lnkUpdate_Click(object sender, RoutedEventArgs e)
        {
            UpdateListOfChapterFromServer();
        }

        private void imgUpdateIcon_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            UpdateListOfChapterFromServer();
        }
        //#endregion


    }
}